// pages/login/mobile/index.js
import WxValidate from '../../../../utils/WxValidate'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    radio: "0",
    mobile: '',
    code: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initValidate();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  initValidate() {
    const rules = {
      mobile: {
        required: true,
        tel: true
      },
      code: {
        required: true,
        rangelength: [6, 6]
      }
    }
    const messages = {
      mobile: {
        required: '请输入手机号',
        tel: '输入正确手机号'
      },
      code: {
        required: '请输入短信验证码',
        rangelength: '请输入6位短信验证码'
      }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  handleGetCode(event) {
    this.setData({
      code: event.detail.value,
    })
  },
  onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },
  goUserName() {
    wx.redirectTo({
      url: '/pages/user/login/userName/index',
    })
  },
  goRegister() {
    wx.navigateTo({
      url: '/pages/user/register/index',
    })
  },
  goForgetPwd() {
    wx.navigateTo({
      url: '/pages/user/forget/index',
    })
  },
  doLogin() {
    var {
      mobile,
      code,
      radio
    } = this.data
    if (radio === '0') {
      getApp().util.showToast("请先同意用户协议")
      return
    }
    if (!this.WxValidate.checkForm(this.data)) {
      const error = this.WxValidate.errorList[0];
      getApp().util.showToast(error.msg)
      return;
    }

    getApp().network.post(getApp().api.mobileLogin, {
      mobile: mobile,
      mobileVerificationCode: code
    }).then(res => {
        wx.setStorageSync(getApp().constant.TOKEN, res)
        getApp().util.showToast("登录成功！")
        getApp().verifyLogin()
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index',
          })
        }, 1000);
    }).catch(() => {})

  },
})